﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace TCP_WCF_Duplex_Message.ServiceLib
{
    // 注意: 使用“重构”菜单上的“重命名”命令，可以同时更改代码和配置文件中的类名“Service1”。
    [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single,ConcurrencyMode=ConcurrencyMode.Multiple)]
    public class MessageService : IMessageService,IDisposable
    {
        List<User> Users;

        public MessageService() 
        {
            Users = new List<User>();
        }

        public void Register(string name) 
        {
            var client = OperationContext.Current.GetCallbackChannel<ICallback>();
            var user = new User(name, client);
            OperationContext.Current.Channel.Closed += Channel_Closed;
            Users.Add(user);
            Console.WriteLine(user.Name + " is Joined.");
        }

        void Channel_Closed(object sender, EventArgs e)
        {
            lock (Users) 
            {
                var u = Users.SingleOrDefault(r => r.Client == (ICallback)sender);
                Console.WriteLine(u.Name + " Lefted.");
                Users.Remove(u);
            }
        }

        public void SendMessage(string name, string msg) 
        {
            Console.WriteLine(name + " have sended " + msg);
            lock (Users) 
            {
                foreach (User u in Users) 
                {
                    u.Client.ReceiveMessage(name, msg); 
                }
            }
            Console.WriteLine("Broadcasted");
        }

        public void Dispose()
        {
            Users.Clear();
        }
    }

    public class User 
    {
        public string Name { get; set; }
        public ICallback Client { get; set; }

        public User(string name, ICallback client) 
        {
            Name = name;
            Client = client;
        }


    }
}
